import React, { useState, useEffect } from 'react';
import {
  Card,
  Button,
  Modal,
  Form,
  Input,
  Select,
  message,
  Drawer,
  Typography,
  Space,
  Tag,
  Popconfirm,
  Row,
  Col,
  Statistic,
  Empty,
  Spin,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  SettingOutlined,
  DeleteOutlined,
  KeyOutlined,
  ReloadOutlined,
  EyeOutlined,
  CopyOutlined,
  ExclamationCircleOutlined,
  MonitorOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import {
  getProjects,
  createProject,
  deleteProject,
  updateProject,
  regenerateApiKey,
  getProjectApiKey,
  type Project,
  type ProjectCreateParams,
} from '@/services/projects';
import './index.less';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;

const Projects: React.FC = () => {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [apiKeyDrawerVisible, setApiKeyDrawerVisible] = useState(false);
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);
  const [form] = Form.useForm();

  // 获取项目列表
  const fetchProjects = async () => {
    setLoading(true);
    try {
      const response = await getProjects();
      if (response.success && response.data) {
        setProjects(response.data.results);
      } else {
        message.error(response.message || '获取项目列表失败');
      }
    } catch (error) {
      console.error('获取项目列表失败:', error);
      message.error('获取项目列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProjects();
  }, []);

  // 创建项目
  const handleCreateProject = async (values: ProjectCreateParams) => {
    try {
      const response = await createProject(values);
      if (response.success) {
        message.success('项目创建成功');
        setCreateModalVisible(false);
        form.resetFields();
        fetchProjects();
      } else {
        message.error(response.message || '创建项目失败');
      }
    } catch (error) {
      console.error('创建项目失败:', error);
      message.error('创建项目失败');
    }
  };

  // 删除项目
  const handleDeleteProject = async (projectId: string) => {
    try {
      await deleteProject(projectId);
      message.success('项目删除成功');
      fetchProjects();
    } catch (error) {
      console.error('删除项目失败:', error);
      message.error('删除项目失败');
    }
  };

  // 更新项目状态
  const handleUpdateProjectStatus = async (projectId: string, status: 'active' | 'inactive' | 'archived') => {
    try {
      const response = await updateProject(projectId, { status });
      if (response.success) {
        message.success('项目状态更新成功');
        fetchProjects();
      } else {
        message.error(response.message || '更新项目状态失败');
      }
    } catch (error) {
      console.error('更新项目状态失败:', error);
      message.error('更新项目状态失败');
    }
  };

  // 重新生成API密钥
  const handleRegenerateApiKey = async (projectId: string) => {
    try {
      const response = await regenerateApiKey(projectId);
      if (response.success) {
        message.success('API Key重新生成成功');
        fetchProjects();
        // 如果当前正在查看该项目的API Key，更新显示
        if (selectedProject?.id === projectId) {
          setSelectedProject(response.data || null);
        }
      } else {
        message.error(response.message || '重新生成API Key失败');
      }
    } catch (error) {
      console.error('重新生成API Key失败:', error);
      message.error('重新生成API Key失败');
    }
  };

  // 查看API Key
  const handleViewApiKey = (project: Project) => {
    setSelectedProject(project);
    setApiKeyDrawerVisible(true);
  };

  // 复制到剪贴板
  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success('已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    const statusConfig = {
      active: { color: 'success', text: '活跃' },
      inactive: { color: 'warning', text: '非活跃' },
      archived: { color: 'default', text: '已归档' },
    };
    const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 计算统计数据
  const stats = {
    total: projects?.length || 0,
    active: projects?.filter(p => p.status === 'active').length || 0,
    inactive: projects?.filter(p => p.status === 'inactive').length || 0,
    archived: projects?.filter(p => p.status === 'archived').length || 0,
    totalErrors: projects?.reduce((sum, p) => sum + (p.error_count || 0), 0) || 0,
  };

  // 跳转到错误日志监控页面
  const handleViewLogs = (projectId: string) => {
    history.push(`/logs/${projectId}`);
  };

  return (
    <div className="projects-container">
      {/* 动态背景 */}
      <div className="projects-background">
        <div className="particles"></div>
        <div className="grid-overlay"></div>
      </div>
      
      <PageContainer
        title="项目管理"
        subTitle="管理您的日志收集项目"
        extra={[
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={fetchProjects}
            loading={loading}
            className="header-button"
          >
            刷新
          </Button>,
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
            className="header-button primary"
          >
            新建项目
          </Button>,
        ]}
      >
        {/* 统计概览 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card className="stats-card">
              <Statistic title="总项目数" value={stats.total} />
            </Card>
          </Col>
          <Col span={6}>
            <Card className="stats-card">
              <Statistic title="活跃项目" value={stats.active} valueStyle={{ color: '#52c41a' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card className="stats-card">
              <Statistic title="非活跃项目" value={stats.inactive} valueStyle={{ color: '#faad14' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card className="stats-card">
              <Statistic title="总错误数" value={stats.totalErrors} valueStyle={{ color: '#ff4d4f' }} />
            </Card>
          </Col>
        </Row>

        {/* 项目列表 */}
        <Spin spinning={loading}>
          {(projects?.length || 0) === 0 ? (
            <Card className="empty-card">
              <Empty
                description="暂无项目"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              >
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={() => setCreateModalVisible(true)}
                  className="create-first-button"
                >
                  创建第一个项目
                </Button>
              </Empty>
            </Card>
          ) : (
            <Row gutter={[16, 16]}>
              {projects?.map((project) => (
                <Col key={project.id} xs={24} sm={12} lg={8} xl={6}>
                  <Card
                    className="project-card"
                    hoverable
                    actions={[
                      <Tooltip key="logs" title="错误监控">
                        <Button
                          type="text"
                          icon={<MonitorOutlined />}
                          onClick={() => handleViewLogs(project.id)}
                          className="card-action-button"
                        />
                      </Tooltip>,
                      <Tooltip key="apikey" title="查看API Key">
                        <Button
                          type="text"
                          icon={<EyeOutlined />}
                          onClick={() => handleViewApiKey(project)}
                          className="card-action-button"
                        />
                      </Tooltip>,
                      <Tooltip key="settings" title="设置">
                        <Button
                          type="text"
                          icon={<SettingOutlined />}
                          className="card-action-button"
                        />
                      </Tooltip>,
                      <Tooltip key="delete" title="删除项目">
                        <Popconfirm
                          title="确定要删除这个项目吗？"
                          description="删除后无法恢复，请谨慎操作。"
                          onConfirm={() => handleDeleteProject(project.id)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button
                            type="text"
                            danger
                            icon={<DeleteOutlined />}
                            className="card-action-button danger"
                          />
                        </Popconfirm>
                      </Tooltip>,
                    ]}
                  >
                    <div className="project-header">
                      <Title level={4} className="project-title">
                        {project.name}
                      </Title>
                      {getStatusTag(project.status)}
                    </div>
                    
                    <Paragraph
                      ellipsis={{ rows: 2, tooltip: project.description }}
                      className="project-description"
                    >
                      {project.description || '暂无描述'}
                    </Paragraph>

                    <div className="project-stats">
                      <Space split={<span className="divider">|</span>}>
                        <Text className="stat-item">
                          <ExclamationCircleOutlined className="stat-icon" />
                          {project.error_count || 0} 错误
                        </Text>
                        <Text className="stat-item">
                          创建于 {new Date(project.created_at).toLocaleDateString()}
                        </Text>
                      </Space>
                    </div>

                    <div className="project-actions">
                      <Select
                        value={project.status}
                        size="small"
                        className="status-select"
                        onChange={(value) => handleUpdateProjectStatus(project.id, value)}
                      >
                        <Option value="active">活跃</Option>
                        <Option value="inactive">非活跃</Option>
                        <Option value="archived">归档</Option>
                      </Select>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          )}
        </Spin>

        {/* 创建项目模态框 */}
        <Modal
          title="创建新项目"
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            form.resetFields();
          }}
          footer={null}
          width={600}
          className="create-modal"
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleCreateProject}
          >
            <Form.Item
              name="name"
              label="项目名称"
              rules={[
                { required: true, message: '请输入项目名称' },
                { min: 2, max: 50, message: '项目名称长度应在2-50个字符之间' },
              ]}
            >
              <Input placeholder="请输入项目名称" />
            </Form.Item>

            <Form.Item
              name="description"
              label="项目描述"
              rules={[
                { max: 200, message: '项目描述不能超过200个字符' },
              ]}
            >
              <Input.TextArea
                rows={4}
                placeholder="请输入项目描述（可选）"
              />
            </Form.Item>

            <Form.Item
              name="status"
              label="项目状态"
              initialValue="active"
            >
              <Select>
                <Option value="active">活跃</Option>
                <Option value="inactive">非活跃</Option>
              </Select>
            </Form.Item>

            <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
              <Space>
                <Button onClick={() => {
                  setCreateModalVisible(false);
                  form.resetFields();
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  创建项目
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* API Key查看抽屉 */}
        <Drawer
          title="API Key"
          placement="right"
          onClose={() => setApiKeyDrawerVisible(false)}
          open={apiKeyDrawerVisible}
          width={500}
          className="api-key-drawer"
        >
          {selectedProject && (
            <div>
              <Title level={4}>{selectedProject.name}</Title>
              <Paragraph>{selectedProject.description}</Paragraph>
              
              <div style={{ marginBottom: 16 }}>
                <Text strong>API Key:</Text>
                <div style={{ 
                  marginTop: 8, 
                  padding: 12, 
                  backgroundColor: '#f5f5f5', 
                  borderRadius: 6,
                  fontFamily: 'monospace',
                  wordBreak: 'break-all'
                }}>
                  {selectedProject.api_key}
                </div>
                <div style={{ marginTop: 8 }}>
                  <Space>
                    <Button
                      icon={<CopyOutlined />}
                      onClick={() => copyToClipboard(selectedProject.api_key)}
                    >
                      复制API Key
                    </Button>
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={() => handleRegenerateApiKey(selectedProject.id)}
                    >
                      重新生成
                    </Button>
                  </Space>
                </div>
              </div>

              <div>
                <Text strong>使用说明:</Text>
                <div style={{ marginTop: 8 }}>
                  <Text code>
                    {`curl -X POST http://your-domain/api/logs/errors/ \\
                    -H "Authorization: Bearer ${selectedProject.api_key}" \\
                    -H "Content-Type: application/json" \\
                    -d '{"message": "your log message"}'`}
                  </Text>
                </div>
              </div>
            </div>
          )}
        </Drawer>
      </PageContainer>
    </div>
  );
};

export default Projects;